package com.zl.tcbnewcar.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.MenuItem;

import com.baidu.location.BDLocation;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.zl.tcbnewcar.R;
import com.zl.tcbnewcar.base.BaseActivity;
import com.zl.tcbnewcar.ui.fragment.CarFragment;
import com.zl.tcbnewcar.ui.fragment.CarHangFragment;
import com.zl.tcbnewcar.ui.fragment.HomeFragment;
import com.zl.tcbnewcar.ui.fragment.PersonFragment;
import com.zl.tcbnewcar.utils.BottomNavigationViewHelper;
import com.zl.tcbnewcar.utils.FragmentHelperReform;
import com.zl.tcbnewcar.utils.LocationUtils;
import com.zl.tcbnewcar.utils.SpUtlis;
import com.zl.tcbnewcar.utils.UpdateManager;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity {


    @BindView(R.id.main_nv)
    BottomNavigationView mainNv;
    private HomeFragment homeFragment;
    private CarFragment carFragment;
    private CarHangFragment carHangFragment;
    private PersonFragment personFragment;
    private FragmentHelperReform helper;
    public static MainActivity mainActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mainActivity = this;
        initView();
        initListener();
        isPermissions();
    }

    /**
     * 是否有储存权限
     */
    private void isPermissions() {
        if (!isPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            applyPermission(Permission.STORAGE, new PermissionListener() {
                @Override
                public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                    isPermissions();
                }

                @Override
                public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                    showToast("您拒绝了储存权限，无法检测更新");
                }
            });
            return;
        }

        if (!isPermission(Manifest.permission.ACCESS_FINE_LOCATION)) {
            applyPermission(Permission.LOCATION, new PermissionListener() {
                @Override
                public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                    isPermissions();
                }

                @Override
                public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                    showToast("您拒绝了定位，无法正常使用部分功能");
                }
            });
            return;
        }

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //检测更新一下
                UpdateManager updateManager = new UpdateManager(mActivity);
                updateManager.isUpdate(true);
            }
        }, 1500);

        //开启定位
        LocationUtils locationUtils = LocationUtils.getInstance(mActivity);
        locationUtils.startLocation();
        locationUtils.setOnLocationListener(new LocationUtils.OnLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                final String data = location.getProvince() + location.getCity() + location.getStreet();
                final String cityCode = location.getCityCode();
                SpUtlis.setCuLocationData(mActivity, cityCode, data, location.getCity());
            }

            @Override
            public void onConnectHotSpotMessage(String s, int i) {
                showToast("定位失败");
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    mainNv.setSelectedItemId(mainNv.getMenu().getItem(2).getItemId());
                    helper.showFragment(carHangFragment);
                    break;
                case 1:
                    mainNv.setSelectedItemId(mainNv.getMenu().getItem(1).getItemId());
                    helper.showFragment(carFragment);
                    break;
                case 2:
                    mainNv.setSelectedItemId(mainNv.getMenu().getItem(0).getItemId());
                    helper.showFragment(homeFragment);
                    break;
                case CarSearchActivity.SEARCHDATA:
                    toKeyWordCar(data);
                    break;
            }
        }
    }

    /**
     * 跳转到车源页面并更新数据
     *
     * @param data
     */
    private void toKeyWordCar(Intent data) {
        final String searchData = data.getStringExtra("searchData");
        helper.showFragment(carFragment);
        mainNv.setSelectedItemId(R.id.main_car);
        //判断任务栈中是否有该Fragment
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        boolean isEnable = false;
        for (Fragment fragment : fragments) {
            if (fragment.getClass().getName().equals(carFragment.getClass().getName())) {
                isEnable = true;
                break;
            }
        }
        if (isEnable) {
            carFragment.updateData(searchData);
        } else {
            showDialog("页面加载中...");
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    hideDialog();
                    carFragment.updateData(searchData);
                }
            }, 800);
        }

//                    helper.showFragment(homeFragment);
    }

    private void initListener() {
        mainNv.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.main_home:
                        helper.showFragment(homeFragment);
                        break;
                    case R.id.main_car:
                        helper.showFragment(carFragment);
                        break;
                    case R.id.main_car_hang:
                        helper.showFragment(carHangFragment);
                        break;
                    case R.id.main_person:
                        helper.showFragment(personFragment);
                        break;
                }
                return true;
            }
        });
    }

    private void initView() {
        BottomNavigationViewHelper.disableShiftMode(mainNv);
        homeFragment = HomeFragment.newInstance();
        carFragment = CarFragment.newInstance();
        carHangFragment = CarHangFragment.newInstance();
        personFragment = PersonFragment.newInstance();
        helper = FragmentHelperReform.builder(mActivity)
                .attach(R.id.main_rl)
                .addFragment(homeFragment)
                .addFragment(carFragment)
                .addFragment(carHangFragment)
                .addFragment(personFragment)
                .commit();
//        helper.showFragment(homeFragment);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (homeFragment.isHidden()) {
                mainNv.setSelectedItemId(R.id.main_home);
                helper.showFragment(homeFragment);
                carFragment.dismissDialog();
            } else {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                mActivity.startActivity(intent);
            }
        }
        return true;
    }
}
